﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using CdcSoftware.Pivotal.Engine.Client.Services.Forms;
using CdcSoftware.Pivotal.Applications.Core.Client;
using CdcSoftware.Pivotal.Engine.UI.DataTypes.Navigation;
using System.Data;
using CdcSoftware.Pivotal.Applications.Core.Common;
using CdcSoftware.Pivotal.Engine.UI.Forms;
using CdcSoftware.Pivotal.Engine;
using CdcSoftware.Pivotal.Engine.Client.Services.Interfaces;
using System.Windows.Forms;
using Microsoft.PointOfService;

namespace Pcm.Retail.Client.FormTasks
{
    public partial class RE_Sale_Serial_Number_Entry : FormClientTask
    {
        #region Variables
        private object mdgvObj;
        private System.ComponentModel.CancelEventArgs mdgvArgsEvent;
        private DataTable mdtSaleSerial;
        private int mRowIdx = -1;
        #endregion

        //private CdcSoftware.Pivotal.WindowsFormControls.PivotalNumber nudSNQty;
        #region Override Methods

        public override void OnFormInitialized()
        {
            try
            {
                base.OnFormInitialized();
                if (this.TaskPad != null)
                {
                    this.TaskPad.Visible = false;
                    // Or remove the TaskPad
                    this.TaskPad.SuspendNotifications();

                    foreach (TaskPadGroup taskPadGroup in this.TaskPad.TaskPadGroups)
                    {
                        taskPadGroup.Items.Clear();
                    }
                    this.TaskPad.TaskPadGroups.Clear();
                    this.TaskPad.ResumeNotifications();
                }
                
                if(mRowIdx == -1) this.SharedLoad();
                mdtSaleSerial = Globals.dtSaleSerialNumber;
                mdgvObj = (DataGridView)Globals.DataGridView;
                mdgvArgsEvent = Globals.Args;
                mRowIdx = Globals.mRowIdx;
                SetDataEdit();
                this.FormView.Dirty = false;
                this.FormControl.GetControlByName("txtProductBarcode").Focus();
            }
            catch (Exception exc)
            {
                Globals.HandleException(exc, true);
            }
        }

        public override bool SaveRecord()
        {
            ((PivotalTimestamp)this.FormControl.GetControlByName("dtpTransactionDate")).TimeValue = TypeConvert.ToDateTime(DateTime.Now);
            this.Apply();
            base.SaveRecord();
            return true;
        }

        public override void OnFormReloaded()
        {
            this.SharedLoad();
            this.FormView.Dirty = false;
            this.FormControl.GetControlByName("txtProductBarcode").Focus();
        }

        #endregion

        #region Methods

        private void SharedLoad()
        {
            try
            {
                ((PivotalTimestamp)this.FormControl.GetControlByName("dtpTransactionDate")).TimeValue = TypeConvert.ToDateTime(DateTime.Now);
                ((PivotalTextBox)this.FormControl.GetControlByName("txtProductBarcode")).Text = 
                ((PivotalTextBox)this.FormControl.GetControlByName("txtProductDescription")).Text = 
                ((PivotalTextBox)this.FormControl.GetControlByName("txtSerialNumber")).Text = 
                ((PivotalTextBox)this.FormControl.GetControlByName("txtTransactionId")).Text =
                ((PivotalTextBox)this.FormControl.GetControlByName("txtProduct")).Text = string.Empty;
                ((PivotalNumber)this.FormControl.GetControlByName("numQuantity")).Value = 1;

                PivotalNumber quantity = ((PivotalNumber)this.FormControl.GetControlByName("numQuantity"));
                
            }
            catch (Exception exc)
            {
                Globals.HandleException(exc, true);
            }
        }

        private void SetDataEdit()
        {
            if (mRowIdx >= 0 && mdtSaleSerial != null && mdtSaleSerial.Rows.Count > 0)
            {
                DataRow saleSerialRow = mdtSaleSerial.Rows[mRowIdx];
                ((PivotalTimestamp)this.FormControl.GetControlByName("dtpTransactionDate")).TimeValue = TypeConvert.ToDateTime(saleSerialRow["Transaction_Date"]);
                ((PivotalTextBox)this.FormControl.GetControlByName("txtProductBarcode")).Text = TypeConvert.ToString(saleSerialRow["Product_Barcode"]);
                ((PivotalTextBox)this.FormControl.GetControlByName("txtProductDescription")).Text = TypeConvert.ToString(saleSerialRow["Product_Id__RE_SKU_Description"]);
                ((PivotalTextBox)this.FormControl.GetControlByName("txtSerialNumber")).Text = TypeConvert.ToString(saleSerialRow["Serial_Number"]);
                ((PivotalTextBox)this.FormControl.GetControlByName("txtTransactionId")).Text = TypeConvert.ToString(saleSerialRow["Transaction_Id"]);

                DataTable dtProduct = Globals.GetDataTable("RE_Product for Barcode? Alt Code1? Alt Code2? Alt Code3?",
                        new object[] { TypeConvert.ToString(saleSerialRow["Product_Barcode"]), TypeConvert.ToString(saleSerialRow["Product_Barcode"]), 
                            TypeConvert.ToString(saleSerialRow["Product_Barcode"]), TypeConvert.ToString(saleSerialRow["Product_Barcode"]) },
                       new string[] { "Product_Id", "RE_Article_Number"});
                if (dtProduct != null && dtProduct.Rows.Count > 0)
                {
                    ((PivotalTextBox)this.FormControl.GetControlByName("txtProduct")).Text = TypeConvert.ToString(dtProduct.Rows[0]["RE_Article_Number"]);
                }

                ((PivotalNumber)this.FormControl.GetControlByName("numQuantity")).Value = TypeConvert.ToInt32(saleSerialRow["Quantity"]);
                Globals.RemoveButtonBarButton("Apply");
            }
        }

        private bool Apply()
        {
            try
            {
                string lsProdBarcode = ((PivotalTextBox)this.FormControl.GetControlByName("txtProductBarcode")).Text.Trim();
                string lsSerialNumber = ((PivotalTextBox)this.FormControl.GetControlByName("txtSerialNumber")).Text.Trim();
                string lsTransactionId = ((PivotalTextBox)this.FormControl.GetControlByName("txtTransactionId")).Text.Trim();
                bool isQtyHasValue = ((PivotalNumber)this.FormControl.GetControlByName("numQuantity")).Value.HasValue;

                if (string.IsNullOrEmpty(lsProdBarcode) || string.IsNullOrEmpty(lsSerialNumber) 
                    || string.IsNullOrEmpty(lsTransactionId) || !(isQtyHasValue)) return true;

                DataRow saleSerialRow = null;
                int rowToFocus = -1;

                if (mRowIdx >= 0 && mdtSaleSerial != null && mdtSaleSerial.Rows.Count > 0)
                {
                    saleSerialRow = mdtSaleSerial.Rows[mRowIdx];
                    rowToFocus = mRowIdx;
                }
                else
                {
                    saleSerialRow = mdtSaleSerial.NewRow();
                }
                saleSerialRow["Transaction_Date"] = ((PivotalTimestamp)this.FormControl.GetControlByName("dtpTransactionDate")).TimeValue;
                saleSerialRow["Product_Barcode"] = lsProdBarcode;
                saleSerialRow["Product_Id__RE_SKU_Description"] = ((PivotalTextBox)this.FormControl.GetControlByName("txtProductDescription")).Text.Trim();
                saleSerialRow["Serial_Number"] = lsSerialNumber;
                saleSerialRow["Transaction_Id"] = ((PivotalTextBox)this.FormControl.GetControlByName("txtTransactionId")).Text.Trim();
                saleSerialRow["Quantity"] = ((PivotalNumber)this.FormControl.GetControlByName("numQuantity")).Value;
                if (mRowIdx == -1) mdtSaleSerial.Rows.Add(saleSerialRow);
                if (rowToFocus == -1) rowToFocus = mdtSaleSerial.Rows.Count == 0 ? 0 : mdtSaleSerial.Rows.Count - 1;

                // Set focus dataGridView
                SetFocusOnSecondaryCell((DataGridView)mdgvObj, "Product_Barcode", rowToFocus);
                SetProductIdUpdatedArticleNumber(rowToFocus);
            }
            catch (Exception ex)
            {
                Globals.HandleException(ex);
                return false;
            }
            return true;
        }

        /// <summary>
        /// Set focus on the next secondary cell .
        /// </summary>
        /// <param name="Sender"></param>
        /// <param name="args"></param>
        private void SetFocusOnSecondaryCell(DataGridView Sender, string columnName, int rowIndex)
        {
            Sender.Focus();
            Sender.CurrentCell = Sender[columnName, rowIndex];
            Sender.BeginEdit(true);
        }

        private void SetProductIdUpdatedArticleNumber(int rowIndex)
        {
            try
            {
                if (!Convert.IsDBNull(mdtSaleSerial.Rows[rowIndex]["Product_Barcode"]) && Convert.IsDBNull(mdtSaleSerial.Rows[rowIndex]["Product_Id"]))
                {
                    DataTable product = Globals.GetDataTable("RE_Product for Barcode? Alt Code1? Alt Code2? Alt Code3?",
                        new object[] { mdtSaleSerial.Rows[rowIndex]["Product_Barcode"], mdtSaleSerial.Rows[rowIndex]["Product_Barcode"], mdtSaleSerial.Rows[rowIndex]["Product_Barcode"],
                    mdtSaleSerial.Rows[rowIndex]["Product_Barcode"]}, "Product_Id");
                    if (product != null && product.Rows.Count > 0)
                    {
                        mdtSaleSerial.Rows[rowIndex]["Product_Id"] = product.Rows[0]["Product_Id"];
                    }
                    else
                    {
                        PivotalMessageBox.Show("No product found for Article Number: " + TypeConvert.ToString(mdtSaleSerial.Rows[rowIndex]["Product_Barcode"]), MessageBoxButtons.OK, MessageBoxIcon.Error);
                        mdtSaleSerial.Rows[rowIndex]["Product_Barcode"] = DBNull.Value;
                    }
                }
            }
            catch (Exception ex)
            {
                Globals.HandleException(ex, true);
            }
        }

        #endregion

    }
}
